#!/usr/bin/env bash
# ${TMOE_CHROOT_PREFIX} mkdir -pv ${TMOE_STARTUP_DIR}
TMP_FILE="${TMPDIR}/.TMOE_CHROOT_STARTUP"
cat >"${TMP_FILE}" <<-ENDOFTMOECHROOT
	#!/usr/bin/env bash
	################
	# You can specify a user. Default is root
	# 您可以指定用户，例如root或ubuntu，默认为root
	# Sie können einen Benutzer angeben
	CHROOT_USER="root"

	# If the value is "default", the home directory will be auto-detected. You can enter an absolute path, for example, "/root".
	HOME_DIR="default"
	################
	# Optional values: "default", "system", "termux", "termux-busybox", "busybox", "toybox", "system-toybox", or an absolute path.
	# You can choose system, termux, or enter the full path. For example, "\${PREFIX}/bin/chroot"
	# In general, "chroot" comes from the "coreutils" package.
	# 当此变量值为system时，将使用系统默认chroot二进制文件所在路径；当其为termux时，将使用 "\${PREFIX}/bin/chroot"。您也可以输入完整路径,例如"/usr/sbin/chroot"
	:<<-'EOF'
	let chroot_bin: &str = match CHROOT_BIN {
		"system"|"default" => "chroot",
		"termux" => "\${PREFIX}/bin/chroot",
		"termux-busybox" => "\${PREFIX}/bin/busybox chroot",
		"busybox" => "buysbox chroot",
		"toybox" => "toybox chroot",
		"system-toybox" => "/system/bin/toybox chroot",
		path @ _ => path, 
	};
	EOF
	CHROOT_BIN="default"

	# Optional values: "default", "system", "termux", "termux-busybox", "busybox", "toybox", "system-toybox", or an absolute path.
	:<<-'EOF'
	let mount_bin: &str = match MOUNT_BIN {
		"system"|"default" => "mount",
		"termux" => "\${PREFIX}/bin/mount",
		"termux-busybox" => "\${PREFIX}/bin/busybox mount",
		"busybox" => "buysbox mount",
		"toybox" => "toybox mount",
		"system-toybox" => "/system/bin/toybox mount",
		path @ _ => path, 
	};
	EOF
	MOUNT_BIN="default"

	# Deprecated values: "busybox", "termux-busybox"
	# In general, "unshare" comes from the "util-linux" package.
	:<<-'EOF'
	let unshare_bin: &str = match UNSHARE_BIN {
		"system"|"default" => "unshare",
		"termux" => "\${PREFIX}/bin/unshare",
		path @ _ => path, 
	};
	EOF
	UNSHARE_BIN="termux"

	ROOTFS_DIR="${DEBIAN_CHROOT}"

	# Optional values: "Android", "linux"
	HOST_DISTRO="${LINUX_DISTRO}"

	# Set the values of CHROOT_BIN and UNSHARE_BIN to termux, and set MOUNT_BIN to termux-busybox.
	# 旧系统/旧版本兼容模式
	# Default is false.
	OLD_ANDROID_VERSION_COMPATIBILITY_MODE=false
	################
	# Load the environment variable file when starting the container. Default is true.
	LOAD_ENV_FILE=true
	CONTAINER_ENV_FILE="\${ROOTFS_DIR}/usr/local/etc/tmoe-linux/environment/container.env"

	# Default is true.
	# 当该值为true时，当前配置信息将会被配置文件里的内容所覆盖。
	LOAD_CHROOT_CONF=true
	CHROOT_CONF_FILE="${CONFIG_FOLDER}/chroot_global.conf"
	################
	# mounts

	# global mount configuration. If the value of "MOUNT_SD" is empty, the file is loaded.
	SD_CONF_FILE="${CONFIG_FOLDER}/rootful/mount_sd.conf"

	# let sd_mount_point = String::from("/media/sd");
	# The lower the number, the higher the priority. The highest priority directory will be mounted to the "/media/sd".
	# 挂载sd，默认为true，SD_DIR为宿主机sd目录。优先级别高，且存在相应目录时，才会被挂载（SD_DIR_0的优先级最高）。默认挂载点为容器内部的"/media/sd"

	# true or false
	# 挂载sd, 可选 true 或 false。 若该值为空，则从全局配置文件"\$SD_CONF_FILE"中读取。
	MOUNT_SD=""

	SD_DIR_0="/data/media/0/Download"
	SD_DIR_1="/storage/self/primary/Download"
	SD_DIR_2="/sdcard/Download"
	SD_DIR_3="${HOME}/sd/Download"
	SD_DIR_4="${HOME}/Downloads"
	SD_DIR_5="${HOME}/Download"

	# global mount configuration. If the value of "MOUNT_TERMUX" is empty, the file is loaded.
	TERMUX_CONF_FILE="${CONFIG_FOLDER}/rootful/mount_termux.conf"

	# If the value is "false", the relevant directory will not be mounted. Default is true.
	MOUNT_TERMUX=""

	# let termux_mount_point = String::from("/media/termux");
	TERMUX_DIR="/data/data/com.termux/files/home"

	# global mount configuration. If the value of "MOUNT_TF" is empty, the file is loaded.
	TF_CONF_FILE="${CONFIG_FOLDER}/rootful/mount_tf.conf"

	# true or false
	MOUNT_TF=""

	# let tf_mount_point = String::from("/media/tf");
	# The value of TF_CARD_LINK is a symbolic link file.
	# TF_CARD_LINK的值为一个软链接文件
	TF_CARD_LINK="${HOME}/storage/external-1"

	MOUNT_TMP=false
	TMP_SOURCE_DIR="${TMPDIR}"
	TMP_MOUNT_POINT="/tmp"

	MOUNT_ITSELF=true
	MOUNT_DEV=true
	MOUNT_PROC=true
	MOUNT_SYS=true
	MOUNT_DEV_PTS=true
	MOUNT_DEV_SHM=true
	FIX_DEV_LINK=true

	MOUNT_GITSTATUS=true
	GITSTATUS_DIR="${CONFIG_FOLDER}/gitstatus"

	# [[enabled, "source", "mount point", "read only"];["mount[]", "mount_src[]", "mount_dst[]", "mount_ro[]"], ["true or false", "src_dir(e.g. /system)", dst_dir, "true or false"]] 
	#
	# ╭───┬───────────────┬─────────────────┬─────────────┬───────────────╮
	# │ # │    enabled    │     source      │ mount point │   read only   │
	# ├───┼───────────────┼─────────────────┼─────────────┼───────────────┤
	# │ 0 │ mount[]       │ mount_src[]     │ mount_dst[] │ mount_ro[]    │
	# │ 1 │ true or false │ src_dir(e.g.    │ dst_dir     │ true or false │
	# │   │               │ /system)        │             │               │
	# ╰───┴───────────────┴─────────────────┴─────────────┴───────────────╯
	#
    # true or false
	mount[0]=false

	# src: source
	mount_src[0]="/system"

	# dst: destination
	# To avoid problems when unmounting, dst(mount point) is a maximum of 2 subdirectories. i.e. You can use "/system" or "/media/system", but not "/media/aa/system/bb".
	# This is a bad design. It is not expected that this constraint will be used in the next edition.
	mount_dst[0]="/system"

	# ro: read only
	mount_ro[0]=true

	#  Mounting the "/data" directory is dangerous and may cause problems with the container.
	mount[1]=false
	mount_src[1]="/data"
	mount_dst[1]="/media/data"
	mount_ro[1]=false

	# You can also manually add mount[2] , mount[3] ...
	################
	# shells
	# let mut shells: Vec<&str> = vec!["zsh", "fish", "bash", "ash", "su"];

	# The default login shell is zsh.
	# 默认登录shell是zsh
	# Die Standard-Login-Shell ist zsh.
	DEFAULT_LOGIN_SHELL_0="/bin/zsh"

	# The lower the number, the higher the priority.
	DEFAULT_LOGIN_SHELL_1="/bin/fish"
	DEFAULT_LOGIN_SHELL_2="/bin/bash"
	DEFAULT_LOGIN_SHELL_3="/bin/ash"
	DEFAULT_LOGIN_SHELL_4="/bin/su"

	# For zsh & bash, "-l" = "--login"
	# For powershell & nushell, they do not have the "-l" arg.
	LOGIN_SHELL_ARG="-l"
	################
	# unshare

	# The unshare command creates new namespaces and then executes the specified program. By  default,  a  new  namespace  persists only as long as it has member processes.  A new namespace can be mad e persistent even when it has no member processes by bind mounting /proc/pid/ns/type files to a filesystem path.  A namespace that has been made persistent in this way can subsequently be entered with nsenter even after the program terminates (except PID namespaces where a permanently running init process is required).  Once  a  persistent namespace is no longer needed, it can be unpersisted by using umount to remove the bind mount.
	UNSHARE_ENABLED=false

	# Unshare the IPC namespace. Default is false.
	# IPC namespace: The process will have an independent namespace for POSIX message queues as well as System V message queues, semaphore sets and shared memory segments.
	UNSHARE_IPC=false

	# Unshare the PID namespace. Default is false.
	# PID namespace: Children will have a distinct set of PID-to-process mappings from their parent.
	UNSHARE_PID=false

	# Unshare the UTS namespace. Default is false.
	# UTS namespace: Setting hostname or domainname will not affect the rest of the system.
	UNSHARE_UTS=false

	# Unshare the mount namespace. Default is false.
	# mount namespace: Mounting and unmounting filesystems will not affect the rest of the system, except for filesystems which are explicitly marked as shared.
	UNSHARE_MOUNT=false

	# When unshare terminates, have signame be sent to the forked child process. Combined with --pid this allows for an easy and reliable killing of the entire process tree below unshare. This option implies --fork.
	# When the value is true and SIGNAME=SIGKILL, the process in the container cannot be terminated with ctrl+c.
	# see this issue: https://github.com/2moe/tmoe/issues/44
	KILL_CHILD=false
	KILL_CHILD_SIGNAME="SIGKILL"

	# Default is true.
	# Just before running the program, mount the proc filesystem at mountpoint (default is /proc).  This is useful when creating a new PID namespace.  It also implies creating a new mount  namespace  since  the  /proc  mount would otherwise mess up existing programs on the system.  The new proc filesystem is explicitly mounted as private (with MS_PRIVATE|MS_REC).
	SHARE_PROC=true
	################
	TMOE_LOCALE_FILE="${CONFIG_FOLDER}/locale.txt"
	DEFAULT_SHELL_CONF="${CONFIG_FOLDER}/default_shell.conf"
	PROC_FD_PATH="/proc/self/fd"
	################
	main() {
	    case "\$1" in
	    i* | -i* | -I*)
	        tmoe t
	        exit 0
	        ;;
	    -vnc* | vnc*) startx11vnc ;;
	    -n* | novnc*) novnc ;;
	    -x) startxsdl ;;
	    *) start_tmoe_gnu_linux_chroot_container ;;
	    esac
	}
	##############
	check_mount_bin() {
	    case \${MOUNT_BIN} in
	    system | default | "") TMOE_MOUNT=mount ;;
	    termux | prefix) TMOE_MOUNT="\${PREFIX}/bin/mount" ;;
	    busybox) TMOE_MOUNT="busybox mount" ;;
	    toybox) TMOE_MOUNT="toybox mount" ;;
	    system-toybox) TMOE_MOUNT="/system/bin/toybox mount" ;;
	    termux-busybox) TMOE_MOUNT="\${PREFIX}/bin/busybox mount" ;;
	    *) TMOE_MOUNT="\${MOUNT_BIN}" ;;
	    esac
	    if [[ \${OLD_ANDROID_VERSION_COMPATIBILITY_MODE} = true ]]; then 
	        TMOE_MOUNT="\${PREFIX}/bin/busybox mount" && CHROOT_BIN="\${PREFIX}/bin/chroot" && UNSHARE_BIN="\${PREFIX}/bin/unshare"
	    fi 
	}
	check_unshare_bin() {
	    case \${UNSHARE_BIN} in
	    system | default | "") TMOE_UNSHARE_BIN=unshare ;;
	    termux | prefix) TMOE_UNSHARE_BIN="\${PREFIX}/bin/unshare" ;;
	    busybox) TMOE_UNSHARE_BIN="busybox unshare" ;;
	    termux-busybox) TMOE_UNSHARE_BIN="\${PREFIX}/bin/busybox unshare" ;;
	    *) TMOE_UNSHARE_BIN="\${UNSHARE_BIN}" ;;
	    esac
	}
	check_chroot_bin() {
	    case \${CHROOT_BIN} in
	    system | default | "") TMOE_CHROOT_BIN=chroot ;;
	    termux | prefix) TMOE_CHROOT_BIN="\${PREFIX}/bin/chroot" ;;
	    busybox) TMOE_CHROOT_BIN="busybox chroot" ;;
	    toybox) TMOE_CHROOT_BIN="toybox chroot" ;;
	    system-toybox) TMOE_CHROOT_BIN="/system/bin/toybox chroot" ;;
	    termux-busybox) TMOE_CHROOT_BIN="\${PREFIX}/bin/busybox chroot" ;;
	    *) TMOE_CHROOT_BIN="\${CHROOT_BIN}" ;;
	    esac
	}
	##############
	check_host_and_root() {
	    case \${HOST_DISTRO} in
	    Android) PREFIX="$PREFIX" ;;
	    *)
	        PREFIX="/usr"
	        case \$(id -u) in
	        0) ;;
	        *)
	            if [[ \$(command -v sudo) ]]; then
	                sudo su -c "bash \${ROOTFS_DIR}/usr/local/etc/tmoe-linux/container/tmoe-linux-container"
	            else
	                su -c "bash \${ROOTFS_DIR}/usr/local/etc/tmoe-linux/container/tmoe-linux-container"
	            fi
	            exit 1
	            ;;
	        esac
	        ;;
	    esac
	}
	##############
	load_global_conf(){
	    if [[ \${LOAD_CHROOT_CONF} = true && -r \${CHROOT_CONF_FILE} ]]; then
	        source \${CHROOT_CONF_FILE}
	    fi
		if [[ -z \${MOUNT_SD} && -r \${SD_CONF_FILE} ]];then
	        source \${SD_CONF_FILE}
		fi
		if [[ -z \${MOUNT_TERMUX} && -r \${TERMUX_CONF_FILE} ]];then
	        source \${TERMUX_CONF_FILE}
		fi
		if [[ -z \${MOUNT_TF} && -r \${TF_CONF_FILE} ]];then
	        source \${TF_CONF_FILE}
		fi
	}
	#----------- 
	start_tmoe_gnu_linux_chroot_container() {
	    check_host_and_root
	    load_global_conf
	    check_mount_bin
	    unset LD_PRELOAD CONTAINER_BIN_PATH
	    #########
	    detect_mount() {
	        MOUNT_DIR="\$1"
	        \$(grep -q " \${MOUNT_DIR%/} " /proc/mounts) && return 0
	        return 1
	    }
	    mount_01() {
	        su -c "\${TMOE_MOUNT} -o bind /\${i} \${ROOTFS_DIR}/\${i}"
	    }
	    mount_ro_or_rw() {
	        local ro_bool=\$1
	        local src_dir=\$2
	        local dst_dir=\$3

	        if (\$(\$ro_bool)); then
	            su -c "\${TMOE_MOUNT} -o bind,ro /\${src_dir} \${ROOTFS_DIR}/\${dst_dir}"
	        else
	            su -c "\${TMOE_MOUNT} -o bind /\${src_dir} \${ROOTFS_DIR}/\${dst_dir}"
	        fi
	    }
	    mkdir_01() {
	        [[ -e "/\${i}" ]] || su -c "mkdir -pv /\${i}"
	    }
	    mkdir_dst() {
	        local dst=\$1
	        [[ -e "\${dst}" ]] || su -c "mkdir -pv \${dst}"
	    }
	    ########
	    # arch mounts itself
	    if [[ \${MOUNT_ITSELF} = true ]]; then
	        if ! detect_mount "\${ROOTFS_DIR}/"; then
	            su -c "\${TMOE_MOUNT} --rbind \${ROOTFS_DIR} \${ROOTFS_DIR}/ &>/dev/null"
	            su -c "\${TMOE_MOUNT} -o remount,exec,suid,relatime,dev \${ROOTFS_DIR}"
	        fi
	    fi
	    ### tmp
	    if [[ \${MOUNT_TMP} = true ]]; then
	        if ! detect_mount "\${ROOTFS_DIR}\${TMP_MOUNT_POINT}"; then
	            su -c "\${TMOE_MOUNT} -o bind \${TMP_SOURCE_DIR} \${ROOTFS_DIR}\${TMP_MOUNT_POINT}"
	        fi
	    fi
	    #########
	    for i in dev proc sys dev/pts dev/shm etc/gitstatus; do
	        if ! detect_mount "\${ROOTFS_DIR}/\${i}"; then
	            case \${i} in
	            dev)
	                # rw,nosuid,relatime,size=12224760k,nr_inodes=3056190,mode=755
	                [[ \${MOUNT_DEV} != true ]] || mount_01
	                ;;
	            proc)
	                if [[ \${UNSHARE_ENABLED} != true || \${SHARE_PROC} != true ]]; then
	                    [[ \${MOUNT_PROC} != true ]] || su -c "\${TMOE_MOUNT} -o rw,nosuid,nodev,noexec,relatime -t \${i} \${i} \${ROOTFS_DIR}/\${i}"
	                fi
	                ;;
	            sys) [[ \${MOUNT_SYS} != true ]] || su -c "\${TMOE_MOUNT} -o rw,nosuid,nodev,noexec,relatime -t \${i}fs \${i}fs \${ROOTFS_DIR}/\${i}" ;;
	            dev/pts)
	                if [[ \${MOUNT_DEV_PTS} = true ]]; then
	                    if ! detect_mount "/\${i}"; then
	                        mkdir_01
	                        su -c "\${TMOE_MOUNT} -o rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000 -t devpts devpts /\${i}"
	                    fi
	                    su -c "\${TMOE_MOUNT} -t devpts devpts \${ROOTFS_DIR}/\${i}"
	                fi
	                ;;
	            dev/shm)
	                if [[ \${MOUNT_DEV_SHM} = true ]]; then
	                    if ! detect_mount "/\${i}"; then
	                        mkdir_01
	                        su -c "\${TMOE_MOUNT} -o rw,nosuid,nodev,mode=1777 -t tmpfs tmpfs /\${i}"
	                    fi
	                    mount_01
	                fi
	                ;;
	            etc/gitstatus) [[ \${MOUNT_GITSTATUS} != true ]] || su -c "\${TMOE_MOUNT} -o bind \${GITSTATUS_DIR} \${ROOTFS_DIR}/\${i}" ;;
	            esac
	        fi
	    done


	    # mount[1]=false
	    # mount_src[1]="/data"
	    # mount_dst[1]="/data"
	    # mount_ro[1]=false
	    for k in "\${!mount[@]}"; do
	        local mount_bool=\${mount[\$k]}
	        local mount_dst=\${mount_dst[\$k]}
	        local mount_src=\${mount_src[\$k]}
	        local mount_ro=\${mount_ro[\$k]}

	        (\$(\$mount_bool)) || continue 

	        (awk -v dst=\$mount_dst 'BEGIN { slash_len = split(dst, dst_arr, "/"); if (slash_len >= 4) exit 1}') || continue
	        
	        local dst_dir="\${ROOTFS_DIR}\$mount_dst"

	        if ! detect_mount "\$dst_dir"; then
	            mkdir_dst \$dst_dir
	            mount_ro_or_rw \$mount_ro \$mount_src \$mount_dst
	        fi

	    done
	    ########
	    if [[ \${FIX_DEV_LINK} = true ]]; then
	        for i in /dev/fd /dev/stdin /dev/stout /dev/sterr /dev/tty0; do
	            if [[ ! -e \${i} && ! -L \${i} ]]; then
	                case \${i} in
	                /dev/fd) su -c "ln -s \${PROC_FD_PATH} \${i} &>/dev/null" ;;
	                /dev/stdin) su -c "ln -s \${PROC_FD_PATH}/0 \${i} &>/dev/null" ;;
	                /dev/stdout) su -c "ln -s \${PROC_FD_PATH}/1 \${i} &>/dev/null" ;;
	                /dev/stderr) su -c "ln -s \${PROC_FD_PATH}/2 \${i} &>/dev/null" ;;
	                /dev/tty0) su -c "ln -s /dev/null \${i} &>/dev/null" ;;
	                esac
	            fi
	        done
	    fi
	    ###############
	    for i in tf termux sd; do
	        if ! detect_mount "\${ROOTFS_DIR}/media/\${i}"; then
	            case \${i} in
	            tf)
	                TF_MOUNT_POINT="/media/tf"
	                if [[ \${MOUNT_TF} = true ]]; then
	                    if [[ -L "\${TF_CARD_LINK}" ]]; then
	                        TF_CARD_FOLDER=\$(readlink \${TF_CARD_LINK} | awk -F '/' '{print \$3}')
	                        if [[ "\$(su -c "ls /mnt/media_rw/\${TF_CARD_FOLDER}")" ]]; then
	                            su -c "\${TMOE_MOUNT} -o bind /mnt/media_rw/\${TF_CARD_FOLDER} \${ROOTFS_DIR}\${TF_MOUNT_POINT} &>/dev/null"
	                        else
	                            su -c "\${TMOE_MOUNT} -o bind \${TF_CARD_LINK} \${ROOTFS_DIR}\${TF_MOUNT_POINT} &>/dev/null"
	                        fi
	                    fi
	                fi
	                ;;
	            #######
	            termux)
	                TERMUX_MOUNT_POINT="/media/termux"
	                if [[ \${MOUNT_TERMUX} = true ]]; then
	                    [[ ! -d "\${TERMUX_DIR}" ]] || su -c "\${TMOE_MOUNT} -o bind \${TERMUX_DIR} \${ROOTFS_DIR}\${TERMUX_MOUNT_POINT} &>/dev/null"
	                fi
	                ;;
	            ###########
	            sd)
	                SD_MOUNT_POINT="/media/sd"
	                if [[ \${MOUNT_SD} = true ]]; then
	                    if [[ "\$(su -c "ls \${SD_DIR_0}" 2>/dev/null)" ]]; then
	                        su -c "\${TMOE_MOUNT} -o bind \${SD_DIR_0} \${ROOTFS_DIR}\${SD_MOUNT_POINT} &>/dev/null"
	                    else
	                        for i in "\${SD_DIR_1}" "\${SD_DIR_2}" "\${SD_DIR_3}" "\${SD_DIR_4}" "\${SD_DIR_5}"; do
	                            if [[ -x \${i} ]]; then
	                                su -c "\${TMOE_MOUNT} -o bind \${i} \${ROOTFS_DIR}\${SD_MOUNT_POINT} &>/dev/null"
	                                break
	                            fi
	                        done
	                    fi
	                fi
	                ;;
	            esac
	        fi
	    done
	    unset i
	    ###########
	    #For Android, do not set the gid and uid of unshare.
	    # if [[ \${UNSHARE_ENABLED} = true && \${CHROOT_USER} != root ]];then
	    #  CHROOT_UID=\$(grep "^\${CHROOT_USER}:" \${ROOTFS_DIR}/etc/passwd | awk -F ':' '{print \$3}')
	    #  CHROOT_GID=\$(grep "^\${CHROOT_USER}:" \${ROOTFS_DIR}/etc/passwd | awk -F ':' '{print \$4}')
	    #  set -- "\${@}" "--setgid" "\${CHROOT_GID}"
	    #  set -- "\${@}" "--setuid" "\${CHROOT_UID}"
	    # fi
	    if [[ \${UNSHARE_ENABLED} = true ]]; then
	        if [[ \${SHARE_PROC} = true ]]; then
	            set -- "\${@}" "--mount-proc"
	            if [[ -e \${ROOTFS_DIR}/proc/stat ]]; then
	                su -c "umount -lvf \${ROOTFS_DIR}/proc || umount \${ROOTFS_DIR}/proc"
	            fi
	        fi
	        [[ \${UNSHARE_IPC} != true ]] || set -- "\${@}" "--ipc"
	        [[ \${UNSHARE_PID} != true ]] || set -- "\${@}" "--pid"
	        [[ \${UNSHARE_UTS} != true ]] || set -- "\${@}" "--uts"
	        [[ \${UNSHARE_MOUNT} != true ]] || set -- "\${@}" "--mount"
	        if [[ \${KILL_CHILD} = true && -n \${KILL_CHILD_SIGNAME} ]]; then
	            set -- "\${@}" "--kill-child=\${KILL_CHILD_SIGNAME}"
	        fi
	        set -- "\${@}" "-R"
	    fi
	    set -- "\${@}" "\${ROOTFS_DIR}"
	    ###########
	    #SET ENV
	    HOST_NAME="localhost"
	    HOST_NAME_FILE="\${ROOTFS_DIR}/etc/hostname"
	    if [[ -s \${HOST_NAME_FILE} ]]; then
	        HOST_NAME=\$(sed -n p \${HOST_NAME_FILE})
	    else
	        [[ ! \$(command -v hostname) ]] || HOST_NAME=\$(hostname -f)
	    fi
	    set -- "\${@}" "/usr/bin/env" "-i"
	    set -- "\${@}" "HOSTNAME=\${HOST_NAME}"
	    set -- "\${@}" "TERM=xterm-256color"
	    set -- "\${@}" "SDL_IM_MODULE=fcitx"
	    set -- "\${@}" "XMODIFIERS=\@im=fcitx"
	    set -- "\${@}" "QT_IM_MODULE=fcitx"
	    set -- "\${@}" "GTK_IM_MODULE=fcitx"
	    set -- "\${@}" "TMOE_CHROOT=true"
	    set -- "\${@}" "TMOE_PROOT=false"
	    set -- "\${@}" "TMPDIR=/tmp"
	    set -- "\${@}" "DISPLAY=:2"
	    set -- "\${@}" "PULSE_SERVER=tcp:127.0.0.1:4713"
	    # CHECK SHELL
	    [[ ! -s \${DEFAULT_SHELL_CONF} ]] || source \${DEFAULT_SHELL_CONF}

	    case \${TMOE_SHELL} in
	        "") 
	        for i in \${DEFAULT_LOGIN_SHELL_0} \${DEFAULT_LOGIN_SHELL_1} \${DEFAULT_LOGIN_SHELL_2} \${DEFAULT_LOGIN_SHELL_3} \${DEFAULT_LOGIN_SHELL_4}; do
	            case "\$i" in
	            */*) New_i="\$i";;
	            *) New_i="/bin/\$i" ;;
	            esac
	            if [[ -f \${ROOTFS_DIR}\${New_i} || -L \${ROOTFS_DIR}\${New_i} ]]; then
	                TMOE_SHELL="\${New_i}"
	                break
	            fi
	        done 
			;;
			*/*) ;;
			*) TMOE_SHELL=/bin/\${TMOE_SHELL} ;;
		esac

	    set -- "\${@}" "SHELL=\${TMOE_SHELL}"

	    # LANG
	    if [[ -e "\${TMOE_LOCALE_FILE}" ]]; then
	        set -- "\${@}" "LANG=\$(head -n 1 \${TMOE_LOCALE_FILE})"
	    else
	        set -- "\${@}" "LANG=zh_CN.UTF-8"
	    fi
	    ############
	    case \${HOME_DIR} in
	    default | "")
	        case \${CHROOT_USER} in
	        root | "") CHROOT_HOME="/root" ;;
	        *)
	            CHROOT_HOME=\$(grep "^\${CHROOT_USER}:" \${ROOTFS_DIR}/etc/passwd | awk -F ':' '{print \$6}')
	            [[ -n \${CHROOT_HOME} ]] || CHROOT_HOME="/home/\${CHROOT_USER}"
	            ;;
	        esac
	        ;;
	    *) CHROOT_HOME="\${HOME_DIR}" ;;
	    esac
	    set -- "\${@}" "HOME=\${CHROOT_HOME}"
	    set -- "\${@}" "USER=\${CHROOT_USER}"
	    if [[ -s \${CONTAINER_ENV_FILE} && \${LOAD_ENV_FILE} = true ]]; then
	        CONTAINER_BIN_PATH=\$(sed -E 's@export\s+@@;/#/d' \${CONTAINER_ENV_FILE} | grep '^PATH=\"' | grep '\${PATH:+:\${PATH}}' | sed 's@\${PATH:+:\${PATH}}\"@:@;s@PATH=\"@@')
	        OLD_IFS="\${IFS}"
	        IFS=\$'\n'
	        CONTAINER_ENV_VAR="\$(sed -E 's@export\s+@@;/#/d;/^PATH=/d' \${CONTAINER_ENV_FILE})"
	        # Do not use double quotes in CONTAINER_ENV_VAR in the for statement
	        for i in \${CONTAINER_ENV_VAR}; do
	            [[ -z \${i} ]] || set -- "\${@}" "\${i}"
	        done
	        IFS="\${OLD_IFS}"
	    fi
	    if [[ \${CHROOT_USER} = root || -z \${CHROOT_USER} ]]; then
	        set -- "\${@}" "PATH=\${CONTAINER_BIN_PATH}/usr/local/sbin:/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/games:/usr/local/games"
	    else
	        set -- "\${@}" "PATH=\${CONTAINER_BIN_PATH}/usr/local/bin:/bin:/usr/bin:/usr/games:/usr/local/games"
	    fi
	    ############
	    # LOGIN SHELL
	    case \${TMOE_SHELL} in
	    */pwsh| */nushell| */nu) 
	        case \${LOGIN_SHELL_ARG} in
	        "-l") LOGIN_SHELL_ARG="" ;;
	        esac
	        ;;
		esac

	    if [[ \${CHROOT_USER} = root || ! -f \${ROOTFS_DIR}/usr/bin/sudo ]]; then
	        case "\${LOGIN_SHELL_ARG}" in
	        "") set -- "\${@}" "\${TMOE_SHELL}" ;;
	        *) set -- "\${@}" "\${TMOE_SHELL}" "\${LOGIN_SHELL_ARG}" ;;
	        esac
		else
	        set -- "\${@}" "/usr/bin/sudo" "-Eu" "\${CHROOT_USER}"
	        case "\${LOGIN_SHELL_ARG}" in
	        "") set -- "\${@}" "\${TMOE_SHELL}" ;;
	        *) set -- "\${@}" "\${TMOE_SHELL}" "\${LOGIN_SHELL_ARG}" ;;
	        esac
	    fi
	    ############
	    #CHROOT/UNSHARE BIN
	    if [[ \${UNSHARE_ENABLED} = true ]]; then
	        check_unshare_bin
	        set -- "\${TMOE_UNSHARE_BIN}" "\${@}"
	    else
	        check_chroot_bin
	        set -- "\${TMOE_CHROOT_BIN}" "\${@}"
	    fi
	    TMOE_CHROOT_EXEC="\${@}"
	    su -c "\${TMOE_CHROOT_EXEC}"
	}
	main "\${@}"
ENDOFTMOECHROOT
# ${DEBIAN_CHROOT}, ${CONFIG_FOLDER}, ${HOME}, $PREFIX, ${LINUX_DISTRO} - \$.
case $(uname -o) in
Android) termux-fix-shebang "${TMP_FILE}" ;;
esac
if [[ ${SYSTEMD_NSPAWN} = true ]]; then
    printf "%s\n" "SYSTEMD_NSPAWN=true" >"${TMPDIR}"/.chroot.conf
else
    printf "%s\n" "SYSTEMD_NSPAWN=false" >"${TMPDIR}"/.chroot.conf
fi
chmod a+rx "${TMP_FILE}" "${TMPDIR}"/.chroot.conf
${TMOE_CHROOT_PREFIX} cp -f "${TMP_FILE}" "${TMOE_STARTUP_SCRIPT}"
${TMOE_CHROOT_PREFIX} mv -f "${TMP_FILE}" "${TMOE_STARTUP_DIR}"/chroot
${TMOE_CHROOT_PREFIX} mv -f "${TMPDIR}"/.chroot.conf "${TMOE_STARTUP_DIR}"/chroot.conf
#${TMOE_CHROOT_PREFIX} chmod a+rx ${TMOE_STARTUP_SCRIPT}

ln -sf "${TMOE_SHARE_DIR}"/container/debian/debian "${PREFIX}"/bin
